package com.huilian.iotbox.data.controller;

import com.huilian.iotbox.data.common.ServerResponse;
import com.huilian.iotbox.data.service.ErrorLogCommonService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @Description:
 * @Date: 2020/3/24 17:55
 */
@ControllerAdvice
@Slf4j
public class BaseController {

    @Autowired
    private ErrorLogCommonService errorLogCommonService;

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public ServerResponse error(Exception e) {
        errorLogCommonService.writerInfoException("全局捕抓异常-报错信息", null, e);
        log.error("全局捕抓异常-报错类：" + e.getClass());
        log.error("全局捕抓异常-报错信息：" + getExceptionAllInformation(e));
        e.printStackTrace();
        return ServerResponse.createByErrorMessage(e.getMessage());
    }

    private String getExceptionAllInformation(Exception e) {
        StackTraceElement stackTraceElement = e.getStackTrace()[0];
        String s1 = "File=" + stackTraceElement.getFileName();
        String s2 = ",Line=" + stackTraceElement.getLineNumber();
        String s3 = ",Method=" + stackTraceElement.getMethodName() + ",";
        StringBuilder sOut = new StringBuilder(s1).append(s2).append(s3).append(e.getMessage()).append(":");
        StackTraceElement[] trace = e.getStackTrace();
        for (StackTraceElement s : trace) {
            sOut.append("\tat " + s + "\r\n");
        }
        return sOut.toString();
    }
}
